package tech.daoxuan.security.browser.authentication;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import tech.daoxuan.security.browser.support.SimpleRespose;
import tech.daoxuan.security.core.properties.LoginType;
import tech.daoxuan.security.core.properties.SecurityProperties;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName DaoxuanAuthenticationFailureHandler
 * @Description TODO
 * @Author 10983
 * @Date 2019/6/20 20:50
 * @Version 1.0
 */
@Component
public class DaoxuanAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private SecurityProperties securityProperties;
    @Autowired
    private ObjectMapper objectMapper;
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {

        logger.info("登陆失败");
        if (LoginType.JSON.equals(securityProperties.getBrowser().getLoginType())){
        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        response.setContentType("application/json;charset=UTF-8");
        //new SimpleRespose(exception.getMessage())返回局部消息
        response.getWriter().write(objectMapper.writeValueAsString(new SimpleRespose(exception.getMessage())));
        }else {
            super.onAuthenticationFailure(request,response,exception);
        }
    }
}
